from django.core.management.base import BaseCommand  #导入基类
from django.utils import timezone #导入时区工具
from datetime import timedelta #导入时间增量工具
from user.models import SystemLog
import csv
from pathlib import Path


class Command(BaseCommand):
    help = "清理指定天数以前的系统日志"

    def add_arguments(self, parser):
        parser.add_argument("--days", type=int, default=30, help="保留多少天内的日志")

    def handle(self, *args, **options):
        days = options["days"]
        cutoff = timezone.now() - timedelta(days=days) #获取当前时间，然后减去 N 天，得到一个‘截止时间’

        # 1️⃣ 找出需要清理的日志
        old_logs = SystemLog.objects.filter(create_time__lt=cutoff) #__lt 表示小于
        count = old_logs.count()

        if count == 0:
            self.stdout.write(self.style.SUCCESS("没有找到过期日志"))
            return
        # self.stdout 打印正常信息; self.stderr 打印错误信息; self 就是 Command 类的实例

        # 2️⃣ 导出这些日志到 CSV
        backup_dir = Path("logs") #定义备份目录
        backup_dir.mkdir(exist_ok=True)
        backup_file = backup_dir / f"systemlog_backup_{timezone.now().date()}.csv"
        # 等价于 backup_file = "E:\\Python练习代码\\python_django\\logs\\systemlog_backup_2025-10-22.csv"；/是拼接符号

        with open(backup_file, "w", newline="", encoding="utf-8") as f:
            writer = csv.writer(f) #创建 CSV 写入器
            writer.writerow(["time", "level", "path", "message", "username", "ip"]) #写入表头
            for log in old_logs:
                writer.writerow([ 
                    log.create_time,
                    log.level,
                    log.path,
                    log.message,
                    log.username,
                    log.ip_address,
                ]) #写入每条日志记录

        self.stdout.write(self.style.SUCCESS(f"已导出 {count} 条日志到 {backup_file}"))

        # 3️⃣ 删除这些旧日志
        old_logs.delete()
        self.stdout.write(self.style.SUCCESS(f"成功删除 {count} 条超过 {days} 天的日志"))
